<template>
  <BoTable
    :columns="columns"
    :request="getNormalList"
    :rowSelection="rowSelection"
    ref="tableRef"
    row-key="id"
    :show-index="true"
  >
    <template #toolbars>
      <Space :size="8">
        <Button type="primary" @click="onAdd"> 新增常规告警策略 </Button>
        <Button :disabled="!selectKeys?.length" @click="onDelete()"
          >删除</Button
        >
      </Space>
    </template>
  </BoTable>
  <FormModal :columns="items">
    <template #bizSysIds="{ model }">
      <FormItemRest>
        <div class="flex items-center justify-between">
          <div>{{ getbizSysIds(model.ancestors) }}</div>
          <Checkbox
            v-model:checked="checkAll"
            :indeterminate="indeterminate"
            @change="(e) => onCheckAllChange(e, model)"
          >
            全选
          </Checkbox>
        </div>
        <Divider />
        <CheckboxGroup
          v-if="hostList.length > 0"
          v-model:value="model.bizSysIds"
          :options="hostList"
          @change="onChange(model)"
        />
      </FormItemRest>
    </template>
    <template #alarmLevel="{ model }">
      <div>
        <RadioGroup
          v-model:value="model.alarmLevel"
          style="margin-bottom: 16px"
        >
          <RadioButton value="1" style="background-color: #3894ff"
            >提示</RadioButton
          >
          <RadioButton value="2" style="background-color: #f9e6b7"
            >普通</RadioButton
          >
          <RadioButton value="3" style="background-color: #ffabab"
            >严重</RadioButton
          >
        </RadioGroup>
        <Process
          :name="itemInfo(model.ancestors).name"
          v-model:value="model.detail"
        ></Process>
      </div>
    </template>
  </FormModal>
</template>
<route lang="json">
{
  "name": "normal",
  "meta": {
    "title": "常规告警策略"
  }
}
</route>
<script setup lang="tsx">
import { computed, ref } from 'vue';
import { isOsEnum, ruleTypeEnum } from '@/constants/alarm';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { listToOption } from '@boeyo/shared';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import {
  Button,
  Checkbox,
  CheckboxGroup,
  Divider,
  FormItemRest,
  Modal,
  RadioButton,
  RadioGroup,
  Space,
  Switch,
  message,
} from 'ant-design-vue';
import {
  addNormal,
  deleteNormal,
  getHostList,
  getIndicatorObjTree,
  getNormalList,
  updateStatus,
} from './api';
import Process from './components/process.vue';

const tableRef = ref();
const selectKeys = ref<any[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values, all) {
      selectKeys.value = values;
    },
  };
});

const dictArr = ['notice_type'];
const { noticeTypeEnum, noticeTypeOptions } = useDicts(dictArr);

// 指标对象树型
const checkAll = ref(false);
const indeterminate = ref(true);
const ancestorsTree = ref([]);
const hostList = ref([]);
const init = () => {
  getIndicatorObjTree({
    isOs: isOsEnum.isOs,
    ruleType: ruleTypeEnum.normal,
  }).then((res) => {
    ancestorsTree.value = res.data;
  });
};

init();

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '告警名称',
    dataIndex: 'ruleName',
  },
  {
    title: '指标对象',
    dataIndex: 'ancestors',
    hideInSearch: true,
    customRender({ record }) {
      record.obj = ['业务对象', '操作系统'];
      const obj = record.obj.join('/');
      return <div>{obj}</div>;
    },
  },
  {
    title: '是否启用',
    dataIndex: 'enable',
    hideInSearch: true,
    customRender({ record }) {
      return (
        <Switch
          v-model:checked={record.enable}
          checked-value='0'
          un-checked-value='1'
          onClick={(checked) => onSwitch(checked, record)}
        ></Switch>
      );
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions() {
      return [
        {
          text: '详情',
          onClick(record) {
            onView(record);
          },
        },
      ];
    },
  },
]);

const items = computed<BoFormProps['columns']>(() => [
  {
    title: '策略名称',
    dataIndex: 'ruleName',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入策略名称',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入策略名称',
    },
  },
  {
    title: '指标对象',
    dataIndex: 'ancestors',
    valueType: 'cascader',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入策略名称',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入策略名称',
      options: ancestorsTree.value,
      fieldNames: {
        label: 'name',
        value: 'id',
        children: 'children',
      },
      onChange: (value) => {
        const selectId = value.at(-1);
        if (selectId) {
          getHostList({
            bizSysId: selectId,
          }).then((res) => {
            hostList.value = listToOption(res.rows, 'name', 'id');
          });
        }
      },
    },
  },
  {
    title: '主机列表',
    dataIndex: 'bizSysIds',
    valueType: 'input',
  },
  {
    title: '告警等级',
    dataIndex: 'alarmLevel',
    valueType: 'input',
  },
]);

const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 1,
});

const onSwitch = async (checked, record: any) => {
  await updateStatus({
    enable: checked,
    id: record.id,
  });
  tableRef.value.refresh();
};

const onView = (record) => {
  open({
    title: (type) => (type === 'info' ? '详情' : '处理'),
    modalType: 'info',
    request: async (params: any) => {
      const { isFalseAlarm, handleDesc, id } = params;
      // await handleAlarm({
      //   isFalseAlarm,
      //   handleDesc,
      //   id,
      // });
      tableRef.value.refresh();
    },
    defaultValue: {
      ...record,
    },
  });
};

// 选择指标对象后回显
const getbizSysIds = computed(() => {
  return (bizSysIds) => {
    const result = [];
    bizSysIds.forEach((item) => {
      findTree(ancestorsTree.value, item, result);
    });
    return result.join(' / ');
  };
});

// 查找树
const findTree = (arr, value, result) => {
  arr.forEach((item) => {
    if (item.id === value) {
      result.push(item.name);
      console.log(item.name, 'item.name');
    } else if (item.children) {
      findTree(item.children, value, result);
    }
  });
  return result;
};
// 获取指标对象回显的告警项或进程名称
const itemInfo = computed(() => {
  return (bizSysIds) => {
    return findItem(bizSysIds.at(0));
  };
});

const findItem = (id) => {
  const info = ancestorsTree.value?.find((item) => item.id === id) || {};
  return {
    name: info.name,
    code: info.code,
    id: info.id,
  };
};
const onAdd = async () => {
  open({
    title: '新增常规告警策略',
    defaultValue: {
      enable: '1',
      bizSysIds: [],
      ancestors: [],
      detail: {
        cpuAlarmCount: '',
        cpuRate: '',
        cpuSymbol: '',
        cpuTime: '',
        cpuTimeUnit: '1',
      },
    },
    request: async (params: any) => {
      const bizSysIds = params.bizSysIds.join();
      const ancestors = params.ancestors.join();
      await addNormal({
        ...params,
        bizSysIds,
        ancestors,
      });
      tableRef.value.refresh();
    },
  });
};

const onChange = (record) => {
  indeterminate.value =
    !!record.bizSysIds.length &&
    record.bizSysIds.length < hostList.value.length;
  checkAll.value = record.bizSysIds.length === hostList.value.length;
};

const onCheckAllChange = (e, record) => {
  console.log(e, record, 'e');

  checkAll.value = e.target.checked;
  indeterminate.value = false;
  record.bizSysIds = e.target.checked
    ? [...hostList.value].map((item) => item.value)
    : [];
};

const onDelete = async (record = null) => {
  const ids = record ? record.id : selectKeys.value.join();
  console.log(ids, 'ids');
  if (!ids) return message.info('请选择要删除的数据');
  Modal.confirm({
    title: '系统提示',
    content: `确定删除当前选中项数据吗?`,
    onOk: async () => {
      await deleteNormal(ids);
      message.success('操作成功');
      tableRef.value.refresh();
    },
  });
};
</script>

<style lang="scss" scoped></style>
